//
//  SecondViewController.m
//  UI - 豆瓣
//
//  Created by dllo on 15/10/27.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "SecondViewController.h"
#import "SecondViewCell.h"
#import "AppTools.h"
#import "Movie.h"
#import "MovieDataViewController.h"
#import "MBProgressHUD.h"
#import "MovieCollectionViewController.h"
#import "MJRefresh.h"
#import "DateBaseSingleton.h"


@interface SecondViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchResultsUpdating, MyTableViewCellDelegate>
@property(nonatomic, retain)UITableView *myTableView;
@property(nonatomic, retain) NSMutableArray *bigArray;
@property(nonatomic, retain)MBProgressHUD *hub;
@property(nonatomic, copy)NSString *movieFilePath;

@property(nonatomic,assign)NSInteger myIndex;
@property(nonatomic,retain)NSMutableArray *searchArray;

@property(nonatomic,retain)UISearchBar *mySearchBar;
@property(nonatomic,retain)UISearchDisplayController *searchDC;

@property(nonatomic,retain)UISearchController *searchController;
@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [[DateBaseSingleton shareDataBase] createtabe];
    self.navigationItem.title = @"电影";
    self.navigationItem.rightBarButtonItem =
    [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_nav_collection@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(rightAction:)];
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.myTableView];
    [self.myTableView registerClass:[SecondViewCell class] forCellReuseIdentifier:@"cell"];
    self.bigArray = [NSMutableArray array];
    self.bigArray = [[DateBaseSingleton shareDataBase]selectMovie];

    
    self.searchArray = [NSMutableArray array];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    //    [searchBar sizeToFit]:设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
    self.myTableView.tableHeaderView = self.searchController.searchBar;
    

    
    
    
    self.myIndex= 0;

    [self addHeaderRefresh];
    [self addFootRefresh];
    
    
    
}

-(void)addHeaderRefresh{

    [self.myTableView addHeaderWithCallback:^{
       
        self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self.hub show:YES];
        self.hub.labelText = @"@玩命加载中@";
        [AppTools getWithName:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php" Block:^(id result) {
            [self.bigArray removeAllObjects];
            NSMutableDictionary *dic = result;
            NSString *reason = [dic objectForKey:@"reason"];
            NSMutableArray *array = [dic objectForKey:@"result"];
            
//            [NSKeyedArchiver archiveRootObject:array toFile:self.movieFilePath];
            
            if ([reason isEqualToString:@"success"]) {
                for (NSMutableDictionary *dic in array) {
                    Movie *movie = [[Movie alloc] init];
                    [movie setValuesForKeysWithDictionary:dic];
                    [[DateBaseSingleton shareDataBase]insertMovie:movie];
                    [self.bigArray addObject:movie];
                    [movie release];
                }
                
                [self.myTableView headerEndRefreshing];
                [self.myTableView reloadData];
                [self.hub hide:YES];
            }else{
                [self.myTableView headerEndRefreshing];
                NSLog(@"请求失败");
            }
            
        }];
        
        
    }];
    [self.myTableView headerBeginRefreshing];
    
}
-(void)addFootRefresh{

    [self.myTableView addFooterWithCallback:^{

        
    }];
    
}

-(void)rightAction: (UIBarButtonItem *)right{

    MovieCollectionViewController *movieCVC = [[MovieCollectionViewController alloc] init];
    [self.navigationController pushViewController:movieCVC animated:YES];
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (self.searchController.active) {
        
        return self.searchArray.count;
    }
    else {
        return self.bigArray.count;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *filePath = @"cell";
   SecondViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:filePath];
    if (self.searchController.active) {
        
        Movie *movie = [self.searchArray objectAtIndex:indexPath.row];
        cell.movie = movie;
    }
    else{
    Movie *movie = [self.bigArray objectAtIndex:indexPath.row];
    cell.movie = movie;
    }
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.MyCellDelegate = self;
    return cell;
}
-(void)movieInfo:(Movie *)movie{

    NSLog(@"name = %@, id = %@", movie.movieName, movie.movieId);
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    Movie *movie = nil;
    
    if (self.searchController.active) {
        
        NSLog(@"选中搜索列表");
        movie = [self.searchArray objectAtIndex:indexPath.row];
        
    }
    else {
        
        NSLog(@"选中所有列表");
        movie = [self.bigArray objectAtIndex:indexPath.row];
        
    }
    
    
    
    MovieDataViewController *movieDataVC = [[MovieDataViewController alloc] init];
        movieDataVC.movieID = movie.movieId;
  
    [self.navigationController pushViewController:movieDataVC animated:YES];
    [movieDataVC release];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 138;
}



-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = [self.searchController.searchBar text];
    
    NSLog(@"===%@",searchString);
    
    [self.searchArray removeAllObjects];
    for (Movie *movie in self.bigArray) {
        
        //rangeOfString:方法是在movieName中搜索是否包含searchText
        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
        //NSNotFound 表示请求操作的某个内容没有发现
        if ([movie.movieName rangeOfString:searchString].location != NSNotFound) {
            
            [self.searchArray addObject:movie];
        }
    }
    NSLog(@"searchArray===%@",self.searchArray);
    
    [self.myTableView reloadData];
}


//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
